#include <windows.h>
#define TIXML_USE_STL
#include "tinyxml.h"
#include "util.h"
#include "GTATradeCodeMap.h"
using namespace utils;

namespace gta
{
	bool CGTATradeCodeMap::InitializeTradecodeByXMLNode( TiXmlNode* rootele )
	{
		TiXmlNode* ele = rootele->FirstChild();
		while(ele != NULL)
		{
			if (ele->ValueStr() == "trade")
			{
				CodeInfo info;
				TiXmlNode* Node;

				Node = ele->FirstChild("code")->FirstChild();
				info.tradecode = Node != NULL ? Node->Value() : "";

				Node = ele->FirstChild("str2api")->FirstChild();
				info.InString2Struct = Node != NULL ? Node->Value() : "";

				Node = ele->FirstChild("OutMsgFunct")->FirstChild();

				std::string tnode = Node != NULL ? Node->Value() : "";
				std::string tlnode = utils::UStringHelper::ToLower(tnode);
				info.OutMsgFunct =tlnode;

				Node = ele->FirstChild("name")->FirstChild();
				info.name = Node != NULL ? Node->Value() : "";
				//
				char tmp1[300] = {0};
				strcpy(tmp1,info.name.c_str());

				char* p  = tmp1;

				UTF8GBKHelper::UTF8ToGBK(p);
				info.name = tmp1;


				///////////////
				Node = ele->FirstChild("TimeOut")->FirstChild();
				info.TimeOut = Node != NULL ? atoi(Node->Value()) : 0;


				Node = ele->FirstChild("InAPIFunct")->FirstChild();
				info.Apifunction = Node != NULL ? Node->Value()  : "";

				Node = ele->FirstChild("OutAPIFunct")->FirstChild();
				info.OutAPIFunct = Node != NULL ? Node->Value() : "";
				this->m_map[info.tradecode] = info;

			}

			ele = ele->NextSibling();
		}
		return true;
	}

	bool CGTATradeCodeMap::InitializeReplycodeByXMLNode( TiXmlNode* rootele )
	{
		TiXmlNode* ele = rootele->FirstChild();
		while(ele != NULL)
		{
			if (ele->ValueStr() == "trade")
			{
				RspInfo info;
				TiXmlNode* Node;

				Node = ele->FirstChild("code")->FirstChild();
				info.tradecode = Node != NULL ? Node->Value() : "";

				Node = ele->FirstChild("saddressip")->FirstChild();
				info.gtaaddr = Node != NULL ? Node->Value() : "";

				Node = ele->FirstChild("iport")->FirstChild();
				info.port = Node != NULL ? atoi(Node->Value()): 0;

				this->m_gtareplymap[info.tradecode]=info;
			}
			ele = ele->NextSibling();
		}
		return true;
	}



	CGTATradeCodeMap& CGTATradeCodeMap::Instance()
	{
		static CGTATradeCodeMap _instance;
		return _instance;
	}

	std::string CGTATradeCodeMap::GetTradeCodeByOutFuncName( std::string outfunc )
	{
		std::string loutfunc = utils::UStringHelper::ToLower(outfunc);

		for(auto item =m_map.begin(); item != m_map.end(); ++item)
		{
			if(item->second.OutMsgFunct == loutfunc)
				return item->first;
		}
		return "";
	}

	CGTATradeCodeMap::CGTATradeCodeMap()
	{

	}

	bool CGTATradeCodeMap::ContainsKey( std::string key )
	{
		return m_map.find(key) != m_map.end();
	}

	CGTATradeCodeMap::RspInfo* CGTATradeCodeMap::GetRspInfo( const char* tradecode )
	{

		auto it = m_gtareplymap.find(tradecode);
		if(it == m_gtareplymap.end())
			return NULL;
		else
			return &m_gtareplymap[tradecode];		
	}

}